<template>
  <div
      class="p-4 h-full flex flex-col relative neo-card neo-border">
    <!-- 组件角落装饰 -->
    <div class="absolute top-4 left-4 w-[0.5px] h-8 pointer-events-none">
      <div class="w-full h-full bg-gradient-to-b from-transparent to-blue-400/70"></div>
    </div>
    <div class="absolute top-4 right-4 w-[0.5px] h-8 pointer-events-none">
      <div class="w-full h-full bg-gradient-to-b from-transparent to-blue-400/70"></div>
    </div>
    <div class="absolute bottom-4 left-4 w-1.5 h-1.5 bg-blue-400/50 pointer-events-none"></div>
    <div class="absolute bottom-4 right-4 w-1.5 h-1.5 bg-blue-400/50 pointer-events-none"></div>

    <!-- 标题 -->
    <h2 class="text-lg font-semibold text-center mb-3 relative z-10 title-neo">
      故障类型分布
    </h2>

    <!-- 切换按钮容器 -->
    <div class="flex gap-1 mb-2 self-start relative z-10">
      <button
          @click="switchToThisMonth"
          :class="[
            currentPeriod === 'thisMonth' ? 'bg-blue-600 text-white shadow-[0_0_8px_rgba(59,130,246,0.5)]' : 'bg-white/5 text-blue-200 hover:bg-white/10 border border-white/10',
            'px-3 py-1.5 text-xs font-medium rounded-lg transition-all duration-300'
          ]"
      >
        本月
      </button>
      <button
          @click="switchToLastMonth"
          :class="[
            currentPeriod === 'lastMonth' ? 'bg-blue-600 text-white shadow-[0_0_8px_rgba(59,130,246,0.5)]' : 'bg-white/5 text-blue-200 hover:bg-white/10 border border-white/10',
            'px-3 py-1.5 text-xs font-medium rounded-lg transition-all duration-300'
          ]"
      >
        上月
      </button>
    </div>

    <!-- 图表容器 -->
    <div ref="chartContainer" class="h-[calc(100%-5rem)] w-full relative z-10"></div>
  </div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, watch} from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const chartContainer = ref(null)
let chartInstance = null
let refreshInterval = null // 定时器引用
const currentPeriod = ref('thisMonth') // 'thisMonth' | 'lastMonth'
const chartData = ref([]) // 用于渲染图表的数据
const allData = ref({thisMonth: [], lastMonth: []}) // 存储所有数据

// 获取数据
const fetchData = async () => {
  try {
    const response = await axios.get('/api/Notice/GetFaultTypeCounts')
    if (response.data.isSuccess) {
      allData.value = response.data.data
      updateChartData()
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 更新图表数据源
const updateChartData = () => {
  chartData.value = currentPeriod.value === 'thisMonth'
      ? allData.value.thisMonth
      : allData.value.lastMonth
}

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  if (chartInstance) {
    chartInstance.dispose()
  }
  chartInstance = echarts.init(chartContainer.value)
  // 设置图表背景透明
  chartInstance.setOption({
    backgroundColor: 'transparent'
  })
  updateChart()
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return

  const data = chartData.value.map(item => ({
    name: item.faultType,
    value: item.count
  }))

  // 计算总和
  const total = data.reduce((sum, item) => sum + item.value, 0)

  // 科技感配色方案
  const colors = [
    '#3B82F6', // 蓝色
    '#8B5CF6', // 紫色
    '#10B981', // 绿色
    '#F59E0B', // 琥珀色
    '#EF4444', // 红色
    '#06B6D4', // 青色
    '#EC4899'  // 粉色
  ]

  const option = {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(15, 23, 42, 0.8)',
      borderColor: 'rgba(59, 130, 246, 0.5)',
      borderWidth: 1,
      textStyle: {
        color: '#E0E7FF'
      },
      formatter: (params) => {
        const percent = ((params.value / total) * 100).toFixed(1)
        return `${params.name}<br/>数量: ${params.value} (${percent}%)`
      }
    },
    series: [
      {
        name: '故障类型分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '50%'],
        data: data || [],
        color: colors,
        label: {
          color: '#93C5FD',
          fontSize: 12,
          formatter: (params) => {
            const percent = ((params.value / total) * 100).toFixed(1)
            return `${params.name}\n${percent}%`
          }
        },
        labelLine: {
          lineStyle: {
            color: 'rgba(147, 197, 253, 0.6)'
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(59, 130, 246, 0.5)'
          }
        }
      }
    ]
  }
  chartInstance.setOption(option)
}
// 启动定时刷新
const startAutoRefresh = () => {
  refreshInterval = setInterval(() => {
    fetchData()
  }, 3000) // 每3秒刷新一次
}
// 停止定时刷新
const stopAutoRefresh = () => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
}
// 切换按钮状态
const switchToThisMonth = () => {
  currentPeriod.value = 'thisMonth'
  updateChartData()
  updateChart()
}

const switchToLastMonth = () => {
  currentPeriod.value = 'lastMonth'
  updateChartData()
  updateChart()
}

// 响应窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(async () => {
  await fetchData()  // 等待数据获取完成
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  initChart()  // 初始化图表
  updateChart()  // 第一次渲染图表（确保数据已加载）
  startAutoRefresh()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  stopAutoRefresh()
})

// 监听按钮切换
watch(currentPeriod, () => {
  updateChart()
})
</script>
